package com.guoqi.oabridge.bridgeImpl

import android.content.Context
import android.net.ConnectivityManager
import android.telephony.TelephonyManager
import com.alibaba.fastjson.JSONObject
import com.guoqi.oabridge.Callback
import com.tencent.smtt.sdk.WebView


/**
 * 网络
 * @author GUOQI
 */
open class NetWorkImpl : IBridge {

    companion object {

        /**
         * 获取运营商名字
         */
        @JvmStatic
        open fun getOperatorName(webView: WebView, param: JSONObject, callback: Callback) {
            val tm = webView.context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            val obj = JSONObject()
            obj["msg"] = tm.simOperatorName
            callback.apply(Callback.setSuccess(obj))
        }

        /**
         * 获取当前网络连接的类型
         */
        @JvmStatic
        open fun getNetworkType(webView: WebView, param: JSONObject, callback: Callback) {
            val cm = webView.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            var msg = "无网络连接"
            cm.activeNetworkInfo?.let {
                msg = when (it.type) {
                    ConnectivityManager.TYPE_WIFI -> "wifi"
                    ConnectivityManager.TYPE_MOBILE -> "移动网络"
                    else -> "其他网络"
                }
            }
            val obj = JSONObject()
            obj["msg"] = msg
            callback.apply(Callback.setSuccess(obj))
        }

        /**
         * 判断是否可上网
         */
        @JvmStatic
        open fun isNetConnected(webView: WebView, param: JSONObject, callback: Callback) {
            val cm = webView.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val obj = JSONObject()
            obj["msg"] = cm.activeNetworkInfo != null && cm.activeNetworkInfo.isConnected
            callback.apply(Callback.setSuccess(obj))
        }


        /**
         * 判断是否wifi连接
         */
        @JvmStatic
        open fun isWifiConnected(webView: WebView, param: JSONObject, callback: Callback) {
            val cm = webView.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = cm.activeNetworkInfo
            var isWifi = false
            networkInfo?.let {
                val networkInfoType = networkInfo.type
                if (networkInfoType == ConnectivityManager.TYPE_WIFI || networkInfoType == ConnectivityManager.TYPE_ETHERNET) {
                    isWifi = networkInfo.isConnected
                }
            }
            val obj = JSONObject()
            obj["msg"] = isWifi
            callback.apply(Callback.setSuccess(obj))
        }
    }
}
